package com.taobao.handler;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import com.taobao.pojo.Line;
import com.taobao.pojo.Title;

public abstract class Handler {

    private Object obj1, obj2;

    public Object getObj1() {
        return obj1;
    }

    public void setObj1(Object obj1) {
        this.obj1 = obj1;
    }

    public Object getObj2() {
        return obj2;
    }

    public void setObj2(Object obj2) {
        this.obj2 = obj2;
    }

    public abstract void handler(Line line) throws Exception;

    protected void setObjectValue(Map<String, String> keyValuePairs, Class<?> clazz, Object obj) throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            String value = keyValuePairs.get(field.getName());
            if (value != null) {
                field.set(obj, value);
            }
        }
    }

    public void hibernate(String titleName, List<Line> unit, Object obj) throws Exception {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            String fieldName = field.getName();
            if (fieldName.length() <= 2 || !fieldName.substring(0, 2).equals("non")) {
                Line target = null;
                for (Line line : unit) {
                    if (line.getKey().equals(fieldName)) {
                        target = line;
                        break;
                    }
                }
                if (target != null) {
                    target.setValue((String) field.get(obj));
                } else {
                    Line line = new Line(new Title(titleName), fieldName, (String) field.get(obj));
                    unit.add(line);
                }
            }
        }
    }
}
